package gnss

import (
	"dgo/goutils/utils"
	"time"
)

type RtcmSSR struct {
	MsgID    uint16
	NaviSys  byte
	GPSTime  time.Time
	UpIntv   int  // s
	SyncFlag byte // Multiple Message Indicator
	Refd     byte // Satellite Reference Datum

	IOD    byte
	ProvID uint16
	SolID  byte
	SatSSR [SATID_MAX]RtcmSSRSat
}

func (this *RtcmSSR) SSRMsgID() {
	switch this.NaviSys {
	case SYS_GPS:
		this.MsgID = 1056 + 4
	case SYS_BD:
		this.MsgID = 1257 + 4
	case SYS_GLO:
		this.MsgID = 1062 + 4
	case SYS_GAL:
		this.MsgID = 1239 + 4
	case SYS_QZS:
		this.MsgID = 1245 + 4
	case SYS_SBS:
		this.MsgID = 1251 + 4
	default:
		return
	}
}

/*
*

	未完成
*/
func (this *RtcmSSR) EncodeSSR4(bb utils.BytesBuilder, startByteN int) {
	startBitN := 0
	// head = 68
	bb.CheckSize(startByteN, 9)
	bb.SetBitU16(startByteN, startBitN, 12, this.MsgID)
	startBitN += 12

	// GPS Epoch Time 1s
	if this.NaviSys == SYS_GLO {
		_, tow := Time2GpsT(GPSTime2UTC(this.GPSTime).Add(10800 * time.Second))
		epoch := RoundU(tow) % 86400
		bb.SetBitU32(startByteN, startBitN, 17, uint32(epoch))
		startBitN += 17
	} else {
		_, tow := Time2GpsT(this.GPSTime)
		epoch := RoundU(tow) % 604800
		bb.SetBitU32(startByteN, startBitN, 20, uint32(epoch))
		startBitN += 20
	}

	/* update interval */
	var idx = 0
	for i := 0; i < 15; i++ {
		if SSR_UP_INTV[i] >= this.UpIntv {
			idx = i
			break
		}
	}
	bb.SetBitU8(startByteN, startBitN, 4, byte(idx))
	startBitN += 4

	bb.SetBitU8(startByteN, startBitN, 1, byte(this.SyncFlag))
	startBitN += 1

	bb.SetBitU8(startByteN, startBitN, 1, byte(this.Refd))
	startBitN += 1

	bb.SetBitU8(startByteN, startBitN, 4, byte(this.IOD))
	startBitN += 4 /* IOD SSR */

	bb.SetBitU32(startByteN, startBitN, 16, uint32(this.ProvID))
	startBitN += 16 /* provider ID */

	bb.SetBitU32(startByteN, startBitN, 4, uint32(this.SolID))
	startBitN += 4 /* solution ID */

	nsat := uint32(0)
	if this.NaviSys == SYS_QZS {
		bb.SetBitU32(startByteN, startBitN, 4, nsat)
		startBitN += 4
	} else {
		bb.SetBitU32(startByteN, startBitN, 6, nsat)
		startBitN += 6
	}
}
